package de.hm.edu.c2dm;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/** 
 * A helper class to handle the C2DM Server Registration
 * 
 * @author Peter Goldenbogen (Munich University of Applied Science)
 * @version 1.0 
 */
public class AuthenticationUtil {
	/**Address to identify to C2DM*/
	private static final String email = "stat.application@googlemail.com";
	/**Password to identify to C2DM*/
	private static final String password = "Fg01h7ab";
	/**The token received by the C2DM Server that is needed to send C2DM messages*/
	private static String auth_token = null;
	
	private AuthenticationUtil() {
		// Utility class cannot get instantiated
	}

	/**
	 * Requests a token via HTTP Request from C2DM Server
	 * 
	 * @return The token that has been returned by the C2DM Server or null
	 * @throws IOException
	 */
	public static String requestToken() throws IOException {
		
		// Create the post data
		// Requires a field with the email and the password
		StringBuilder builder = new StringBuilder();
		builder.append("Email=").append(email);
		builder.append("&Passwd=").append(password);
		builder.append("&accountType=GOOGLE");
		builder.append("&source=C2dmServer");
		builder.append("&service=ac2dm");

		// Setup the Http Post to request server token
		byte[] data = builder.toString().getBytes();
		URL url = new URL("https://www.google.com/accounts/ClientLogin");
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setUseCaches(false);
		con.setDoOutput(true);
		con.setRequestMethod("POST");
		con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		con.setRequestProperty("Content-Length", Integer.toString(data.length));

		// Issue the HTTP POST request
		OutputStream output = con.getOutputStream();
		output.write(data);
		output.close();

		// Read the response
		BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String line = null;
		String auth_key = null;
		while ((line = reader.readLine()) != null) {
			if (line.startsWith("Auth=")) {
				auth_key = line.substring(5);
			}
		}

		// return authentication token
		return auth_key;
	}

	public static String getAuth_token() {
		return auth_token;
	}

	public static void setAuth_token(String auth_token) {
		AuthenticationUtil.auth_token = auth_token;
	}
}
